/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bashe.business.ejb;

import han.bashe.common.converter.JmsConverter;
import han.bashe.common.entity.BasheEntityConstants;
import han.bashe.common.exception.BasheErrorCode;
import han.bashe.common.exception.BasheException;
import han.bashe.common.message.NormalizedMessage;
import han.bashe.common.message.RequestHelper;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.TransactionAttribute;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.commons.logging.LogFactory;



/**
 * @Author Kent
 */

@MessageDriven
(mappedName = "han.bashe.gateway.Queue",
    name = "JmsGatewayMDB",
    activationConfig = {
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
        }
)
public class JmsGatewayMDB implements MessageListener {

	@EJB
	Pipeline pipeline;
	
	@TransactionAttribute(value = javax.ejb.TransactionAttributeType.NOT_SUPPORTED)
	public void onMessage(Message mes) {
		try {
			if(! (mes instanceof TextMessage)){
				throw new BasheException(BasheErrorCode.JMS_MESSAGE_TYPE_ERROR,"only support javax.jms.TextMessage");
			}
			
			
			
			NormalizedMessage msg = JmsConverter.toNormalized((TextMessage)mes);
			RequestHelper rh = new RequestHelper(msg);
			rh.setOrginMsgType(BasheEntityConstants.JMS_TYPE);
			msg = pipeline.process(msg);
			
			
			
		} catch (BasheException e) {
			org.apache.commons.logging.Log log = LogFactory.getLog(JmsGatewayMDB.class);
			log.error("JmsGatewayMDB.onMessage() error",e);
			
			
		}catch (Exception e) {
			org.apache.commons.logging.Log  log = LogFactory.getLog(JmsGatewayMDB.class);
			log.error("JmsGatewayMDB.onMessage() error",e);
			
			
		}
		
	}

}
